package com.xinyuan.trade.Activity;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

import com.xinyuan.trade.R;
import com.xinyuan.trade.Fragment.BaseFragment;
import com.xinyuan.trade.Fragment.HomeFragment;
import com.xinyuan.trade.Fragment.NewFragment;
import com.xinyuan.trade.Fragment.SettingFragment;
import com.xinyuan.trade.Fragment.TypeFragment;
import com.xinyuan.trade.Utils.PLog;
import com.xinyuan.trade.Widght.Toast;

/**
 * 首页
 * @author daiy
 *
 */
public class MainActivity extends BaseActivity {

	public static MainActivity mActivity = null;
	private Resources resources;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mActivity = this;
		resources = getResources();
		initTab();
	}
	
	/************************** Tab布局 ***************************************/
	// 定义FragmentTabHost对象
	public FragmentTabHost mTabHost;
	// 定义一个布局
	private LayoutInflater layoutInflater;
	// 定义数组来存放Fragment界面
	private Class<?> fragmentArray[] = {
			HomeFragment.class, TypeFragment.class, NewFragment.class,
			SettingFragment.class };
	// 定义数组来存放按钮图片
	private int mImageViewArray[] = { R.drawable.btn_menu_home,
			R.drawable.btn_menu_type, R.drawable.btn_menu_new, R.drawable.btn_menu_setting };
	
	// Tab选项卡的文字
	private int mTextviewArray[] = {R.string.menu_home, R.string.menu_type, R.string.menu_new, R.string.menu_setting };
	private HashMap<String, View> tabViewItem = new HashMap<String, View>();

	private void initTab() {
		// 实例化布局对象
		layoutInflater = LayoutInflater.from(this);

		// 实例化TabHost对象，得到TabHost
		mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
		mTabHost.setup(self, getSupportFragmentManager(), R.id.realtabcontent);
		uiAdapter
				.setMargin(mTabHost, LayoutParams.MATCH_PARENT, 76, 0, 0, 0, 0);
		uiAdapter.setPadding(mTabHost, 0, 0, 0, 0);
		mTabHost.setOnTabChangedListener(new OnTabChangeListener() {

			@Override
			public void onTabChanged(String tabId) {
				TextView textView = (TextView) tabViewItem.get(tabId)
						.findViewById(R.id.txt_menu);

				Iterator iterator = tabViewItem.entrySet().iterator();
				while (iterator.hasNext()) {
					Map.Entry entry = (Map.Entry) iterator.next();

					TextView tv_view = (TextView) ((View) entry.getValue())
							.findViewById(R.id.txt_menu);
					tv_view.setTextColor(textView == tv_view ? resources
							.getColor(R.color.menu_text_press) : resources
							.getColor(R.color.menu_text));
				}
			}
		});

		// 得到fragment的个数
		int count = fragmentArray.length;
		for (int i = 0; i < count; i++) {
			// 为每一个Tab按钮设置图标、文字和内容
			TabSpec tabSpec = mTabHost.newTabSpec(getString(mTextviewArray[i]))
					.setIndicator(getTabItemView(i));
			// 将Tab按钮添加进Tab选项卡中
			mTabHost.addTab(tabSpec, fragmentArray[i], null);
		}
	}

	/**
	 * 给Tab按钮设置图标和文字
	 */
	private View getTabItemView(int index) {
		View view = layoutInflater
				.inflate(R.layout.layout_main_menu_item, null);
		uiAdapter.setMargin(view, 120, LayoutParams.MATCH_PARENT, 0, 0, 0, 0);
		
		// 图标
		ImageView imageView = (ImageView) view.findViewById(R.id.img_menu);
		imageView.setImageResource(mImageViewArray[index]);
		uiAdapter.setMargin(imageView, 52, uiAdapter.CalcHeight(52, 1, 1), 0, 0, 0, 0);
		
		// 文字
		TextView textView = (TextView) view.findViewById(R.id.txt_menu);
		textView.setText(mTextviewArray[index]);
		uiAdapter.setTextSize(textView, 16);

		tabViewItem.put(getString(mTextviewArray[index]), view);
		return view;
	}
	
	public void onResume() {
		super.onResume();
	}

	public void onPause() {
		super.onPause();
	}
	
	/**
	 * 获取子类中的数量
	 * 
	 * @return
	 */
	public int getCurChildFragmentCount() {
		FragmentManager fm = getCurChildFragmentManager();
		if (fm != null)
			return fm.getBackStackEntryCount();
		return 0;
	}
	
	/**
	 * 跳转
	 * 
	 * @param key
	 * @param fragment
	 * @param canBack
	 */
	public void replaceChildFragment(String key, BaseFragment fragment,
			boolean canBack) {

		FragmentTransaction ft = getCurChildFragmentManager()
				.beginTransaction();
		ft.replace(R.id.child_fragment, fragment, key);
		ft.setTransition(FragmentTransaction.TRANSIT_ENTER_MASK);
		if (canBack)
			ft.addToBackStack(null);
		try {
			ft.commitAllowingStateLoss();
		} catch (Exception e) {
			PLog.e("%s", e.getMessage());
		}
	}
	
	/**
	 * 返回当前的子fragment管理
	 * 
	 * @return
	 */
	public FragmentManager getCurChildFragmentManager() {
		FragmentManager fm = getSupportFragmentManager().findFragmentByTag(
				mTabHost.getCurrentTabTag()).getChildFragmentManager();
		return fm;
	}
	
	public boolean Back() {
		FragmentManager fm = getCurChildFragmentManager();
		PLog.e("%s  fm.getBackStackEntryCount() = %s",
				mTabHost.getCurrentTabTag(), fm.getBackStackEntryCount());
		if (fm.getBackStackEntryCount() > 1) {
			fm.popBackStack();
			return true;
		}
		if (fm.getBackStackEntryCount() <= 1) {
			exit();
			return true;
		}
		return false;
	}
	
	boolean isExit;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (Back()) {
				return true;
			} 
		}
		return super.onKeyDown(keyCode, event);
	}

	public void exit() {
		if (!isExit) {
			isExit = true;
			Toast.show(self, "再按一次退出程序");
			mHandler.sendEmptyMessageDelayed(0, 2000);
		} else {
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_HOME);
			startActivity(intent);
			System.exit(0);
		}
	}

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			isExit = false;
		}
	};
}
